import requests
import urllib.parse
import hashlib
import json
import csv
import os
import time

# 此处填入自己的微信Authorization
auth = ''
# Authorization: wxmp.******
def getdetail(id):
    url ='https://www.xiaohongshu.com/fe_api/burdock/weixin/v2/note/'+id+'/single_feed'
    xsign = "X{0}".format(
        hashlib.md5("{0}WSUDD".format(url.replace("https://www.xiaohongshu.com", "")).encode("utf-8")).hexdigest())

    headers = {
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-cn',
        'Connection': 'keep-alive',
        'Content-Type':'application/json',
        # 'Device-Fingerprint': '',
        # 'Cookie': '',
        'Host': 'www.xiaohongshu.com',
        'Referer': '',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.10(0x18000a28) NetType/WIFI Language/zh_CN',
        'Host':'www.xiaohongshu.com',
        'Authorization': auth,
        'X-Sign': xsign,
    }

    response = requests.get(
        url=url,
        headers=headers,
    )
    content = response.content
    # 转换成字符串
    string = content.decode('utf-8')
    # 把字符串转成python数据类型
    results = json.loads(string)
    print(results)
    return results

def save(data):
    file = open(data['title']+'.csv', 'w', encoding='utf-8', newline='')
    csv_writer = csv.DictWriter(file, fieldnames=['cover','isLiked', 'haveGoodsSeller', 'inCensor', 'poi', 'censorTip', 'type', 'time', 'id', 'cooperateBinds', 'imageList', 'hashTags', 'isCollected', 'commentList', 'canShareMoment', 'ats', 'likes', 'collects', 'shareCount', 'comments', 'title', 'desc', 'comments', 'collects', 'user'])
    csv_writer.writeheader()
    csv_writer.writerow(data)

if __name__ == '__main__':
    id = '61a601a0000000002103c1a4'
    data = getdetail(id)['data']
    save(data)
